{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 正确关闭文件的必要性"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# python关闭文件的方式"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## try finally"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['test content manager\\n']\n",
      "False\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "try:\n",
    "    f = open('resource/test_with.txt')\n",
    "    print(f.readlines())\n",
    "finally:\n",
    "    print(f.closed)\n",
    "    if f:\n",
    "        f.close()\n",
    "        print(f.closed)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## with\n",
    "1. 只要正确实现了__enter__,__exit__方法的对象都可以使用\n",
    "1. 调用以上两个方法是由Python解释器，自动调用的\n",
    "1. 调用时机，资源"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 使用内建的with"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['test content manager\\n']\n"
     ]
    }
   ],
   "source": [
    "with open('resource/test_with.txt') as f:\n",
    "    print(f.readlines())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 实现自己的关闭方式\n",
    "1. 实现管理多个文件的类"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Begin\n",
      "Query info about Bob...\n",
      "Query info about Bob...\n",
      "exc_type: None\n",
      "End\n"
     ]
    }
   ],
   "source": [
    "class Query(object):\n",
    "\n",
    "    def __init__(self, name):\n",
    "        self.name = name\n",
    "\n",
    "    def __enter__(self):\n",
    "        print('Begin')\n",
    "        return self\n",
    "\n",
    "    def __exit__(self, exc_type, exc_value, traceback):\n",
    "        print('exc_type:',exc_type)\n",
    "        if exc_type:\n",
    "            print('Error')\n",
    "        else:\n",
    "            print('End')\n",
    "\n",
    "    def query(self):\n",
    "        print('Query info about %s...' % self.name)\n",
    "        self.query1()\n",
    "        \n",
    "\n",
    "    def query1(self):\n",
    "        print('Query info about %s...' % self.name)\n",
    "        \n",
    "with Query('Bob') as q:\n",
    "    q.query()        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['test content manager\\n']"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "class Files:\n",
    "    files = dict()\n",
    "    def add(self,tag,filename):\n",
    "        self.files[tag] = open(filename)\n",
    "    def read(self,tag):\n",
    "        return self.files[tag].readlines()\n",
    "f= Files()    \n",
    "f.add('f1','resource/test_with.txt')\n",
    "f.read('f1')\n",
    "f.add('f2','resource/test_with.txt')\n",
    "f.read('f2')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  },
  "latex_envs": {
   "LaTeX_envs_menu_present": true,
   "autoclose": false,
   "autocomplete": true,
   "bibliofile": "biblio.bib",
   "cite_by": "apalike",
   "current_citInitial": 1,
   "eqLabelWithNumbers": true,
   "eqNumInitial": 1,
   "hotkeys": {
    "equation": "Ctrl-E",
    "itemize": "Ctrl-I"
   },
   "labels_anchors": false,
   "latex_user_defs": false,
   "report_style_numbering": false,
   "user_envs_cfg": false
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
